﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyPublisher.Storage
{
    public class StorageConnectionString
    {
        public const string PROVIDER_KEY = "provider";
        public const string USERNAME_KEY = "username";
        public const string PASSWORD_KEY = "password";
        public const string PATH_KEY = "path";

        private Dictionary<string, string> KeyValues { get; set; }

        public StorageConnectionString()
        {
            this.KeyValues = new Dictionary<string, string>()
            {
                {PROVIDER_KEY,string.Empty},
                {USERNAME_KEY,string.Empty},
                {PASSWORD_KEY,string.Empty},
                {PATH_KEY,string.Empty},
            };
        }

        public string Domain
        {
            get
            {
                string[] splits = UserName.Split(new char[] { '\\' });
                if (splits.Length > 1)
                {
                    return splits[0];
                }

                return string.Empty;
            }
        }

        public string Provider
        {
            get { return KeyValues[PROVIDER_KEY]; }
            set { KeyValues[PROVIDER_KEY] = value; }
        }
        public string UserName
        {
            get 
            {
                string[] splits = KeyValues[USERNAME_KEY].Split(new char[] { '\\' });
                if (splits.Length > 1)
                {
                    return splits[0];
                }
                return splits[0];
            }
            set { KeyValues[USERNAME_KEY] = value;}
        }
        public string Password
        {
            get { return KeyValues[PASSWORD_KEY]; }
            set { KeyValues[PASSWORD_KEY] = value; }
        }
        public string Path
        {
            get { return KeyValues[PATH_KEY]; }
            set { KeyValues[PATH_KEY] = value; }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> keyValue in KeyValues)
            {
                sb.AppendFormat("{0}={1};", keyValue.Key, keyValue.Value);
            }
            return sb.ToString().TrimEnd(new char[] { ';' });
        }

        public static StorageConnectionString Parse(string connString)
        {
            connString = connString.Trim(new char[] { ';' });
            StorageConnectionString conn = new StorageConnectionString();

            string[] splits = connString.Split(new char[] { ';' });
            foreach (string split in splits)
            {
                string[] keyvalue = split.Split(new char[]{'='});
                conn.KeyValues[keyvalue[0]] = keyvalue[1];
            }

            return conn;
        }
    }
}
